﻿using AutoMapper;
using B.S.BasicData.Api.Write.Application.Command.User;
using B.S.BasicData.Domian.Entitys;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infastructure.Interface;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.S.BasicData.Api.Write.Application.Handler.User
{
    public class UpdateUserHandler : IRequestHandler<UpdateUserCommand, ApiResult<int>>
    {
        private readonly IMapper _mapper;
        private readonly IBaseRepository<UsersModel> _userRepository;
        public UpdateUserHandler(IMapper mapper, IBaseRepository<UsersModel> userRepository)
        {
            _mapper = mapper;
            _userRepository = userRepository;
        }
        /// <summary>
        /// 用户修改
        /// </summary>
        /// <param name="request">请求参数</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回受影响行数</returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<int>> Handle(UpdateUserCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
             var users = _userRepository.GetAll().FirstOrDefault(p => p.UserName == request.UserName && p.Id!=request.Id);
            if (users != null)
            {
                result.Code = StatusEnum.Error;
                result.Message = "用户名重复";
                return Task.FromResult(result);
            }
            var user = _userRepository.GetAll().Where(x => x.Id == request.Id).FirstOrDefault();
            if(user!=null)
            {
                user = _mapper.Map(request, user);
                user.UpdateTime = DateTime.Now;
                user.Updater = "李四";
            }
            var res = _userRepository.Update(user);
            if (res > 0)
            {
                result.Code = StatusEnum.OK;
                result.Data = res;
                result.Message = "修改成功";
            }
            else
            {
                result.Code = StatusEnum.Fail;
                result.Data = res;
                result.Message = "修改失败";
            }
            return Task.FromResult(result);
        }
    }
}
